//
//  BM_YellowVC.m
//  BaoYouYou
//
//  Created by MZY on 16/12/4.
//  Copyright © 2016年 caobo56. All rights reserved.
//

#import "BM_YellowVC.h"
#import <AVFoundation/AVFoundation.h>
#import "HTTPRequestManager.h"
#import "UIImage+Color.h"

@interface BM_YellowVC ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
    UIImageView *imageV;
}
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) UILabel *resultLabel;
@property (nonatomic, strong) UILabel *infoLabel;

@end

@implementation BM_YellowVC

- (UIImage *)getImageWithColor:(UIColor *)color{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGFloat scale = [[UIScreen mainScreen] scale];
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,[color CGColor]);
    CGContextFillRect(context,rect);
    CGContextSaveGState(context);
    CGContextRestoreGState(context);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void)createView{

    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WidthOfScreen, 0)];
    backView.top = 64+10;
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.text= @"请在白天光照好时靠近额头或脸拍照，\n保证成像框正中央为一块儿完整皮肤。";
    label.textColor = UIColorFromRGB(0X1a1a1a);
    label.font = [UIFont systemFontOfSize:15];
    [label sizeToFit];
    label.centerX = WidthOfScreen/2;
    label.top = 64+rateWidth(30);
    [self.view addSubview:label];

    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, rateWidth(205), rateWidth(205))];
    lineView.backgroundColor = [UIColor clearColor];
    lineView.layer.borderColor = UIColorFromRGB(0X999999).CGColor;
    lineView.layer.borderWidth = 1;
    lineView.centerX = WidthOfScreen/2;
    lineView.top = label.bottom+rateWidth(30);
    [self.view addSubview:lineView];

    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, rateWidth(197), rateWidth(197))];
    _imageView.centerX = WidthOfScreen/2;
    _imageView.image = [UIImage imageNamed:@"yellow"];
    _imageView.centerY = lineView.centerY;
    [self.view addSubview:_imageView];

    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake(0, 0, 180, 44);
    sureBtn.centerX = WidthOfScreen/2;
    sureBtn.top = _imageView.bottom+rateWidth(50);
    [sureBtn setTitle:@"拍照" forState:UIControlStateNormal];
    [sureBtn setBackgroundImage:[self getImageWithColor:UIColorFromRGB(0xE77A7D)] forState:UIControlStateNormal];
    sureBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [sureBtn addTarget:self action:@selector(getPhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];

    backView.height = sureBtn.bottom - 64 + rateWidth(30);

    imageV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"boy_girl"]];
    imageV.top = backView.bottom+rateWidth(30);
    imageV.width = WidthOfScreen - rateWidth(50)*2;
    imageV.height = 40;
    imageV.centerX = WidthOfScreen/2;
    imageV.hidden = YES;
    [self.view addSubview:imageV];

    if (INCH_4) {
        backView.height = 333;
        sureBtn.bottom = backView.bottom- 20;
    }else if (INCH_47){
        backView.height = 395;
        sureBtn.bottom = backView.bottom- 50;
    }else{
        backView.height = 421;
        sureBtn.bottom = backView.bottom- 50;
    }

    _resultLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, WidthOfScreen, 15)];
    _resultLabel.centerY = imageV.centerY;
    _resultLabel.textAlignment = NSTextAlignmentCenter;
    _resultLabel.text= @"";
    _resultLabel.textColor = UIColorFromRGB(0X1a1a1a);
    _resultLabel.hidden = YES;
    [self.view addSubview:_resultLabel];

    _infoLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    _infoLabel.textAlignment = NSTextAlignmentLeft;
    _infoLabel.numberOfLines = 0;
    _infoLabel.text= @"免责声明：由于拍照条件不同或宝宝个体差异，上述结果\n仅供初步筛查用，不能当做医学诊断依据。";
    _infoLabel.textColor = UIColorFromRGB(0X999999);
    _infoLabel.font = [UIFont systemFontOfSize:11];
    _infoLabel.hidden = YES;
    [_infoLabel sizeToFit];
    _infoLabel.centerX = WidthOfScreen/2;
    _infoLabel.top = imageV.bottom+rateWidth(20);
    [self.view addSubview:_infoLabel];


}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"新生儿黄疸识别";
    self.view.backgroundColor = UIColorFromRGB(0Xf1f2f3);
    [self createView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(void)getPhoto{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusDenied){
        [self.view toastMessage:@"您未开启摄像头权限"];
        return;
    }
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
    }
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    }
    [self presentViewController:_imagePicker animated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    [picker dismissViewControllerAnimated:YES completion:nil];
    _imageView.image = image;
    [self postImage];
}

-(void)setResult:(NSDictionary *)dic{
    _resultLabel.hidden = NO;
    imageV.hidden = NO;
    _infoLabel.hidden = NO;
    _resultLabel.text = [NSString stringWithFormat:@"黄疸概率:%.f％",[dic[@"aurigoProb"] doubleValue]];
}


-(void)postImage{

    UIImage *image = _imageView.image;
    NSData *data = [image resizeForUpload];
    [self.view showLoadingWithMessage:@"正在分析图片请稍后"];
    WeakSelf
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * userid = @"0";
    if ([user valueForKey:@"userid"]) {
        userid = [NSString stringWithFormat:@"%@",[user valueForKey:@"userid"]];
    }
    
    NSString * fileName = [NSString stringWithFormat:@"%@_yellow.jpeg",userid];
    NSString * url = [NSString stringWithFormat:@"http://183.174.228.55:8089/youbaobao/app/doAurigoProb?userId=%@",userid];
    [[HTTPRequestManager sharedManager].requestSerializer
     setValue:@"multipart/form-data;charset=utf-8"
     forHTTPHeaderField:@"Content-Type"];
    
    [[HTTPRequestManager sharedManager] POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [weakSelf.view hideLodingView];
        [weakSelf.view toastMessage:@"上传成功"];
        NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        if (result.length) {
            result = [result stringByReplacingOccurrencesOfString:@"null" withString:@"\"\""];

            NSError *__autoreleasing error = nil;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
            if (error) {
                [weakSelf.view toastMessage:@"网络请求错误，请稍后重试"];
            }else{
                [weakSelf setResult:dic];
            }
        }else{
            [weakSelf.view toastMessage:@"网络请求错误，请稍后重试"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf.view hideLodingView];
        [weakSelf.view toastMessage:@"网络请求错误，请稍后重试"];
        
    }];
}

@end
